// 自定義通知組件，兼容瀏覽器通知
var Notification2 = function (title, options) {
    this.data = $.extend({
        url: null,
        time: 30000,
        offset: 'rb',
    }, options.data);
    var body = options.body || '';
    var url = this.data.url;
    var offset = this.data.offset;
    // 未找到會員
    if (!url) {
        this.index = layer.alert(body, {
            title: title,
            btn: ['關閉'],
            offset: offset
        });
        return;
    }
    // 找到會員
    this.index = layer.confirm(body, {
        title: title,
        btn: ['查看會員資料', '關閉'],
        offset: offset,
        yes: function () {
            setTimeout(function () {
                window.open(url);
            }, 500);
        }
    });
}

Notification2.prototype.close = function () {
    layer.close(this.index);
}

Notification2.prototype.onclick = function () {
    window.open(this.data.url, '_blank');
    this.close();
}

// 檢測用户授權
try {
    Notification.requestPermission(function (permission) {
        if ("granted" == permission) {
            Notification2 = Notification;
        } else {
            console.log('用户未授權');
        }
    });
} catch (error) {
    console.log('瀏覽器不支持 Notification');
}

$(function () {
    // 新订单通知
    var rechargePollID = setInterval(function () {
        console.log('開始檢測新儲值');

        $.getJSON('/recharge/notification/new_seven_apply', function (response) {
            console.log('RechargePoll response', response);

            if (!response.status) return;

            if (response.code == '403') {
                clearInterval(rechargePollID);
                return;
            }

            var title = '7-11儲值通知';
            var body  = '有 ' + response.data.count + ' 筆新的儲值申請';
            var url   = response.data.url || '';

            var n     = new Notification2(title, {
                requireInteraction: true,
                body: body,
                data: {
                    url: url,
                    time: 30000
                },
                tag: 'new_seven_apply',
                icon: '/images/seven-icon.png',
            });
            // console.log(n.data.url);
            // 自動關閉
            setTimeout(function () {
                n.close();
            }, n.data.time);
            // 打開鏈接
            if (url) {
                n.onclick = function () {
                    window.open(n.data.url, '_blank');
                    this.close();
                }
            }
        });
    }, 30000);
});
